const mysql = require('mysql2/promise');

const pool = mysql.createPool({
    host: '182.160.6.140',
    user: 'root',
    password: '123456',
    database: 'binance_klines',
    waitForConnections: true,
    connectionLimit: 10,
    queueLimit: 0
});

// 获取表名
function getTableName(interval) {
    return `kline_${interval}_enhanced`;
}

// 批量插入K线数据
async function batchInsertKlines(symbol, interval, klines) {
    if (!klines || klines.length === 0) return;

    const tableName = getTableName(interval);
    const values = klines.map(k => [
        symbol,
        parseInt(k[0]),  // open_time
        k[1],           // open_price
        k[2],           // high_price
        k[3],           // low_price
        k[4],           // close_price
        k[5],           // volume
        parseInt(k[6]), // close_time
        k[7],           // quote_volume
        parseInt(k[8]), // trades_count
        k[9],           // taker_buy_volume
        k[10]           // taker_buy_quote_volume
    ]);

    const sql = `INSERT INTO ${tableName} 
        (symbol, open_time, open_price, high_price, low_price, close_price, 
         volume, close_time, quote_volume, trades_count, taker_buy_volume, 
         taker_buy_quote_volume) 
        VALUES ? 
        ON DUPLICATE KEY UPDATE
        open_price = VALUES(open_price),
        high_price = VALUES(high_price),
        low_price = VALUES(low_price),
        close_price = VALUES(close_price),
        volume = VALUES(volume),
        close_time = VALUES(close_time),
        quote_volume = VALUES(quote_volume),
        trades_count = VALUES(trades_count),
        taker_buy_volume = VALUES(taker_buy_volume),
        taker_buy_quote_volume = VALUES(taker_buy_quote_volume)`;

    try {
        await pool.query(sql, [values]);
    } catch (error) {
        console.error(`Error inserting klines into ${tableName}:`, error);
        throw error;
    }
}

// 获取最新的K线时间
async function getLatestKlineTime(symbol, interval) {
    const tableName = getTableName(interval);
    try {
        const [rows] = await pool.query(
            `SELECT MAX(open_time) as latest_time FROM ${tableName} WHERE symbol = ?`,
            [symbol]
        );
        return rows[0].latest_time;
    } catch (error) {
        console.error(`Error getting latest kline time from ${tableName}:`, error);
        return null;
    }
}

// 从数据库获取K线数据
async function getKlinesFromDB(symbol, interval, startTime, endTime) {
    const tableName = getTableName(interval);
    try {
        const [rows] = await pool.query(
            `SELECT * FROM ${tableName} 
             WHERE symbol = ? AND open_time >= ? AND open_time <= ?
             ORDER BY open_time ASC`,
            [symbol, startTime, endTime]
        );
        
        return rows.map(row => [
            row.open_time.toString(),
            row.open_price.toString(),
            row.high_price.toString(),
            row.low_price.toString(),
            row.close_price.toString(),
            row.volume.toString(),
            row.close_time.toString(),
            row.quote_volume.toString(),
            row.trades_count.toString(),
            row.taker_buy_volume.toString(),
            row.taker_buy_quote_volume.toString()
        ]);
    } catch (error) {
        console.error(`Error getting klines from ${tableName}:`, error);
        return [];
    }
}

module.exports = {
    batchInsertKlines,
    getLatestKlineTime,
    getKlinesFromDB
}; 